//
//  RequestService+Music.swift
//  NDAi
//
//  Created by 丸子 on 2024/7/26.
//

import UIKit
import Alamofire
import Swime
extension RequestService {

    func music_create(name:String, type:Int, lyrics:String, lyric_desc:String, style_text:String, is_instrumental:Int, completeClosure: ((String) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "types":"\(type)"])
        var dict:[String:Any] = [:]
        if type == 1 {
            dict = ["timestamp":time,
                    "sign":sign,
                    "types":type,
                    "lyric_desc":lyric_desc]
        }else {
            dict = ["timestamp":time,
                         "sign":sign,
                         "music_name":name,
                         "types":type,
                         "music_lyric":lyrics,
                         "style_text":style_text,
                         "is_instrumental":is_instrumental]
        }
        session.request("\(apiHost)/api/music/create_music",
                        method: .post,
                        parameters: dict, encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let checkId = result["checkId"] as? String else { return }
                completeClosure?(checkId)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func music_homelist(completeClosure: (([MusicModel]) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/music/default_list",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String : Any], let defaultList = result["defaultList"] as? [[String: Any]],let model = [MusicModel].deserialize(from: defaultList) else {
                    failureClosure?("")
                    return
                }
                completeClosure?(model.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func createLyric_desc(lyric_desc:String, completeClosure: ((String) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
  
        session.request("\(apiHost)/api/music/generate_lyric_desc",
                        method: .post,
                        parameters:["timestamp":time,
                                    "sign":sign,
                                    "lyric_desc":lyric_desc], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let lyric_desc = result["lyric_desc"] as? String else { return }
                completeClosure?(lyric_desc)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func createLyric(lyric_desc:String, completeClosure: ((String) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
  
        session.request("\(apiHost)/api/music/generate_lyrics",
                        method: .post,
                        parameters:["timestamp":time,
                                    "sign":sign,
                                    "optimizeLyrics":lyric_desc], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let lyric_desc = result["lyrics"] as? String else { return }
                completeClosure?(lyric_desc)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func getCheckMusic(checkId:String, completeClosure: ((MusicModel?) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "outTradeNo":checkId])
        session.request("\(apiHost)/api/music/check_info",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign,
                                     "outTradeNo":checkId])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String: Any], let model = MusicModel.deserialize(from: result) else { return }
                completeClosure?(model)
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func UserMusicList(page:Int, completeClosure: (([MusicModel]) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "page":"\(page)"])
  
        session.request("\(apiHost)/api/music/result_list",
                        method: .post,
                        parameters:["timestamp":time,
                                    "sign":sign,
                                    "page":page], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any], let list = result["list"] as? [[String: Any]], let models = [MusicModel].deserialize(from: list) else { return }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func UserDeleteMusic(id:String, completeClosure: ((String) -> Void)?, failureClosure: ((String?) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time,
                                                               "id":id])
  
        session.request("\(apiHost)/api/music/delete_music",
                        method: .post,
                        parameters:["timestamp":time,
                                    "sign":sign,
                                    "id":id], encoding: JSONEncoding.default)
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String:Any] else { return }
                completeClosure?("")
            case let .failure(error):
                failureClosure?(error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func RandomStyle(completeClosure: ((String) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/music/random_style",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String: Any], let style = result["style_text"] as? String else { return }
                completeClosure?(style)
            case let .failure(error):
                NDProgressHUD.show(message: error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    func requestStyle(completeClosure: (([MusicStyle]) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/music/style_list",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String: Any], let style = result["style"] as? [[String:Any]], let models = [MusicStyle].deserialize(from: style) else { return }
                completeClosure?(models.compactMap { $0 })
            case let .failure(error):
                NDProgressHUD.show(message: error.localizedDescription)
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
    
    
    func musicConfig(completeClosure: (([String: Any]) -> Void)?) {
        let time = getTimestamp()
        let sign = RequestService.instance.generateHash(data: ["systemId":system_id,
                                                               "timestamp":time])
        session.request("\(apiHost)/api/music/get_config",
                        method: .get,
                        parameters: ["timestamp":time,
                                     "sign":sign
                                    ])
        .responseData { resp in
            self.statRequest(resp)
            switch resp.result{
            case let .success(data):
                let JSON = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers)
                guard let jsonDic = JSON as? [String: Any],
                      let current = jsonDic["code"] as? String, current == "200",
                      let result = jsonDic["result"] as? [String : Any], let content = result["content"] as? [String : Any] else {
                    return
                }
                completeClosure?(content)
            case let .failure(error):
                XLog.d("getActivityMsg", "sync fail", error)
            }
        }
    }
}

